<template>
  <div class="upload-container">
    <div v-if="resultUrl">
      <el-link target="_blank" :href="resultUrl" :underline="false">
        <el-button size="small" type="primary">点击下载</el-button>
      </el-link>
    </div>
    <el-upload
      v-loading="uploadLoading"
      :data="uploadData"
      :action="uploadImageUrl"
      :limit="1"
      :headers="myHeaders"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="beforeUpload"
      :on-remove="remove"
      drag>
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将文件拖拽到此处 或者 <em>点击上传</em>
      </div>
      <template v-if="!imageUrl&&showWaringLabel" #tip>
        <span class="waring-label">{{ waringLabel }}</span>
      </template>
    </el-upload>
  </div>
</template>

<script>
import { getRefreshToken, getToken } from '@/utils/auth'
import defaultImg from '@/assets/img/default_img.jpg'
import { refreshToken } from '@/api/sys/user/oauth2'
export default {
  name: 'UploadFile',
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    dir: {
      type: String,
      default: ''
    },
    extension: {
      type: String,
      default: ''
    },
    uploadLabel: {
      type: String,
      default: '上传文件'
    },
    limit: {
      type: Number,
      required: false,
      default: 10
    },
    basePath: {
      type: String,
      default: ''
    },
    showWaringLabel: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue'],
  data() {
    return {
      uploadImageUrl: import.meta.env.VITE_APP_BASE_API + '/oss/attachment/upload',
      uploadData: { base_path: this.basePath },
      myHeaders: { Authorization: getToken() },
      imageExtension: ['bmp', 'jpg', 'jpeg', 'png', 'gif'],
      extensions: [],
      uploadLoading: false,
      resultUrl: undefined,
      waringLabel: '只能上传' + this.extension + '文件，且不超过' + this.limit + 'M'
    }
  },
  computed: {
    imageUrl() {
      if (this.resultUrl) {
        const fileExtension = this.getFileExtension(this.resultUrl)
        if (fileExtension !== '' && this.imageExtension.includes(fileExtension)) {
          return this.resultUrl
        }
        return defaultImg
      }
      return ''
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(val) {
        try {
          const array = JSON.parse(val)
          this.resultUrl = array[0].url
        } catch (e) {
          this.resultUrl = val
        }
      }
    }
  },
  created() {
    let extension = this.extension.replace(/(^\s+)|(\s+$)/g, '')
    extension = extension.replace(/\s/g, '')
    this.extensions = extension.split(',')
    if (this.dir !== '') {
      this.uploadImageUrl += '?dir=' + this.dir
    }
  },
  methods: {
    emitInput(val) {
      this.$emit('update:modelValue', val)
    },
    handleSuccess(response, file) {
      if (response.success) {
        this.uploadLoading = false
        this.resultUrl = response.data
        this.emitInput(this.resultUrl)
      } else if (response.code === 200004) {
        const refreshTokenData = getRefreshToken()
        refreshToken(refreshTokenData).then(res => {
          if (res.data.success) {
            this.$store.userStore.setToken(res.data.data.accessToken)
            this.myHeaders = { Authorization: res.data.data.accessToken }
            file.status = 'ready'
            // this.$refs.upload.$forceUpdate()
            this.$refs.upload.submit()
          } else {
            this.$message.error('Token失效，请重新登录')
          }
        })
      } else {
        this.$message.error(response.msg)
      }
    },
    remove() {
      this.resultUrl = undefined
      this.emitInput(undefined)
    },
    handleError(response) {
      this.uploadLoading = false
      if (response.msg) {
        this.$message.error(response.msg)
      } else {
        this.$message.error('上传失败')
      }
    },
    beforeUpload(file) {
      // 扩展名判断
      const fileExtension = this.getFileExtension(file.name)
      if (fileExtension === '') {
        this.$message.error('文件必须有扩展名')
        return false
      }

      if (this.extension !== '') {
        const isFileExtension = this.extensions.includes(fileExtension)
        if (!isFileExtension) {
          this.$message.error('上传文件只能是' + this.extension + '格式!')
          return false
        }
      }
      // 判断文件大小
      const isLimitSize = file.size / 1024 / 1024 < this.limit
      if (!isLimitSize) {
        this.$message.error('上传头像图片大小不能超过 ' + this.limit + 'MB!')
      }
      if (isLimitSize) {
        this.uploadLoading = true
      }
      return isLimitSize
    },
    getFileExtension(fileName) {
      if (fileName.lastIndexOf('.') > 0) {
        return fileName.substring(fileName.lastIndexOf('.') + 1)
      }
      return ''
    }
  }
}
</script>
